# -*- coding: utf-8 -*-
from django.forms.fields import CharField, MultiValueField
from django.forms.widgets import TextInput, MultiWidget, HiddenInput
from django import forms
from django.utils.safestring import mark_safe
import hashlib
import random
from django.utils.translation import ugettext as _


class CaptchaTextInput(forms.widgets.MultiWidget):
    """A simple captcha field. Remember to set your own salt."""
    def __init__(self,attrs=None):
        widgets = (
                TextInput(attrs),
                HiddenInput(attrs),
                )
        super(CaptchaTextInput,self).__init__(widgets,attrs)

    def decompress(self,value):
        if value:
            return value.split(',')
        return [None,None]


    def render(self, name, value, attrs=None):
        ints = (random.randint(0,9),random.randint(0,9),)
        answer = hashlib.sha1("mysalt" + str(sum(ints))).hexdigest() #with salt

        # Control question to prevent spam
        extra = _("What is %(num1)d + %(num2)d? ") % {'num1': ints[0], 'num2': ints[1]}
        value = [u'', answer,]
        return mark_safe(extra + super(CaptchaTextInput, self).render(name, value, attrs=attrs))


class CaptchaField(forms.fields.MultiValueField):
    widget=CaptchaTextInput

    def __init__(self, *args,**kwargs):
        fields = (
                CharField(),
                CharField(show_hidden_initial=True), 
                )
        super(CaptchaField,self).__init__(fields=fields, *args, **kwargs)

    def compress(self,data_list):
        if data_list:
            return ','.join(data_list)
        return None

    def label(self, value):
        return "test" + super(CaptchaField, self).label

    def clean(self, value):
        super(CaptchaField, self).clean(value)
        response = value[0].strip()

        if not hashlib.sha1("mysalt" + str(response)).hexdigest() == value[1]:
            # Your answer was wrong. To prove you are not a spam robot you will have to try again.
            raise forms.ValidationError(_("Your answer to the control question is wrong. To prove you are not a robot you will have to try again."))
        return value

